import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import "./register.css";
import axios from '../../api/axios';
import { useNavigate } from 'react-router-dom';

const API_URL = '/register';

const Register = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const onFinish = async (values) => {
    setLoading(true);
    try {
      const response = await axios.post(API_URL, values);
      message.success('注册成功！');
      console.log(response.data); // 可以在这里处理注册成功的逻辑，比如跳转页面
      navigate('/login'); // 注册成功后跳转到登录页面
    } catch (error) {
      message.error('注册失败，请重试！');
      console.error('Register error:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form
      className="register-container"
      onFinish={onFinish}
    >
      <div className="register_title">用户注册</div>
      <Form.Item
        label="账号"
        name="username"
        rules={[{ required: true, message: '请输入账号' }]}
      >
        <Input placeholder="请输入账号" />
      </Form.Item>
      <Form.Item
        label="密码"
        name="password"
        rules={[{ required: true, message: '请输入密码' }]}
      >
        <Input.Password placeholder="请输入密码" />
      </Form.Item>
      <Form.Item
        label="确认密码"
        name="confirmPassword"
        dependencies={['password']}
        rules={[
          { required: true, message: '请确认密码' },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次输入的密码不一致'));
            },
          }),
        ]}
      >
        <Input.Password placeholder="请确认密码" />
      </Form.Item>
      <Form.Item className="register-button">
        <Button type="primary" htmlType="submit" loading={loading}>注册</Button>
      </Form.Item>
    </Form>
  );
};

export default Register;